#!/usr/bin/env python

from optparse import OptionParser
import sys, os

if not 'MQ_LOG_LEVEL' in os.environ:
    os.environ['MQ_LOG_LEVEL'] = '-1'

sys.path.insert(0, 'build/lib.macosx-10.5-i386-2.5')
from imq import MQConnection, MQMessage
from imq import MQ_BROKER_HOST_PROPERTY, MQ_BROKER_PORT_PROPERTY, MQ_CONNECTION_TYPE_PROPERTY, \
    MQ_CLIENT_ACKNOWLEDGE, MQ_SESSION_SYNC_RECEIVE, MQ_QUEUE_DESTINATION, MQ_TOPIC_DESTINATION, \
    MQ_TEXT_MESSAGE, MQ_MESSAGE_TYPE_HEADER_PROPERTY, MQ_REDELIVERED_HEADER_PROPERTY
from imq import MQ_STRING_TYPE, MQ_INT32_TYPE



def consumer(host, port, name, type):
    conn = MQConnection({MQ_BROKER_HOST_PROPERTY: (MQ_STRING_TYPE, host),
            MQ_BROKER_PORT_PROPERTY: (MQ_INT32_TYPE, port),
            MQ_CONNECTION_TYPE_PROPERTY: (MQ_STRING_TYPE, "TCP")}, "guest", "guest")
    sess = conn.create_session(False, MQ_CLIENT_ACKNOWLEDGE, MQ_SESSION_SYNC_RECEIVE)
    cons = sess.create_consumer(sess.create_destination(name, type))
    conn.start()

    while True:
        print "Waiting for message ..."
        mess = cons.receive_message_wait()

        if mess.type() != MQ_TEXT_MESSAGE:
            print "Received mesage is not MQ_TEXT_MESSAGE type."
            mess.acknowledge_messages()
            continue

        text = mess.get_text()

        if 'END' == text:
            mess.acknowledge_messages()
            break

        print "Received message:", mess.get_text()

        properties = mess.get_properties()

        if 'index' in properties:
            print '\tProperty index=%d' % properties.get("index")[1]

        headers = mess.get_headers()
        print "\tHeader redelivered=%s" % headers[MQ_REDELIVERED_HEADER_PROPERTY][1]

        if MQ_MESSAGE_TYPE_HEADER_PROPERTY in headers:
            print "\tHeader message-type=%s" % headers[MQ_MESSAGE_TYPE_HEADER_PROPERTY][1]

        mess.acknowledge_messages()


if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option("--host", action="store", dest="host", default="localhost")
    parser.add_option("--port", action="store", dest="port", default=7676, type="int")
    parser.add_option("--destination_name", action="store", dest="destination_name", default="example_producerconsumer_dest")
    parser.add_option("--type", action="store", dest="type", choices=("q", "t",), default="q")
    (options, args) = parser.parse_args()

    args = {'host' : options.host, 'port' : options.port, 'name' : options.destination_name,
        'type' : 't' == options.type and MQ_TOPIC_DESTINATION or MQ_QUEUE_DESTINATION}

    consumer(**args)
